package java8Up;

import java.time.*;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;

/**
 * @author Fang Ruichuan
 * @date 2022-10-27 15:59
 */
public class LocalDateDemo {
    public static void main(String[] args) {
//        testNow();
//        testOf();
//        testWith();
//        testCompare();
        System.out.println(dateToLocalDateTime(new Date()));
        System.out.println(localDateTimeToDate(LocalDateTime.now()));
    }

    //java.util.Date类型转LocalDateTime
    public static LocalDateTime dateToLocalDateTime(Date date) {
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        return instant.atZone(zoneId).toLocalDateTime();
    }

    //java.time.LocalDateTime转java.util.Date
    public static Date localDateTimeToDate(LocalDateTime localDateTime) {
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = localDateTime.atZone(zoneId);
        return Date.from(zdt.toInstant());
    }

    static void testCompare() {
        LocalDate first = LocalDate.now();
        LocalDate second = LocalDate.of(2015, 12, 25);
        System.out.println(first.isBefore(second));
        System.out.println(first.isAfter(second));
    }


    static void testNow() {
        System.out.println(LocalDate.now());
        System.out.println(LocalTime.now());
        System.out.println(LocalDateTime.now());
    }

    static void testOf() {
        System.out.println(LocalDate.of(2015, 12, 20));
        System.out.println(LocalTime.of(15, 36, 48));
        System.out.println(LocalDateTime.of(2013, 9, 21, 5, 58, 24));
    }

    static void testWith() {
        LocalDate localDate = LocalDate.of(2022, 10, 27);
        // 获取本月的第一天
        System.out.println("本月第一天：" + localDate.with(TemporalAdjusters.firstDayOfMonth()));
        // 获取本月的最后一天
        System.out.println("本月最后一天：" + localDate.with(TemporalAdjusters.lastDayOfMonth()));
        // 本年第一天
        System.out.println("本年第一天: " + localDate.with(TemporalAdjusters.firstDayOfYear()));
        // 本年最后一天
        System.out.println("本年最后一天: " + localDate.with(TemporalAdjusters.lastDayOfYear()));
        // 下一个周几的操作
        System.out.println("上周四: " + localDate.with(TemporalAdjusters.previous(DayOfWeek.THURSDAY)));
        System.out.println("下周四: " + localDate.with(TemporalAdjusters.next(DayOfWeek.THURSDAY)));
        // 本月第二周的周五
        System.out.println("本月第二周的周五: " + localDate.with(TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.FRIDAY)));
        // 下一个月的第一天
        System.out.println("下一个月的第一天: " + localDate.with(TemporalAdjusters.firstDayOfNextMonth()));
        // 加一天
        System.out.println("加一天: " + localDate.plusDays(1));
        // 加一周
        System.out.println("加一周: " + localDate.plusWeeks(1));
        // 加一个月
        System.out.println("加一个月: " + localDate.plusMonths(1));
    }
}
